// 横幅列表交互逻辑
(function() {
if (document.readyState !== 'loading') {
    init();
} else {
    document.addEventListener('DOMContentLoaded', init);
}

function init() {
    const tabId = 'banner_list';
    let container = document.querySelector(`[data-tab-id="${tabId}"]`);
    let $container = $(container);

    if (!container) return;

    let currentEditRow = null;
    let originalData = {};
    let activeSelectId = 0;  // 关联商品用于打开与关闭选择框

    const headers = {
          'Content-Type': 'application/json',
          'X-CSRFToken': getCSRFToken(),
          'X-Requested-With': 'XMLHttpRequest'
        };

    // 1. 监听点击事件:click
    container.addEventListener('click', function (e) {
      const editBtn = e.target.closest('.edit-banner');          // 编辑
      const saveBtn = e.target.closest('.save-banner');          // 保存
      const cancelBtn = e.target.closest('.cancel-edit');        // 作废
      const uploadBtn = e.target.closest('.image-upload-btn');   // 上传图片
      const deleteBtn = e.target.closest('.delete-banner');      // 删除
      const newBtn = e.target.closest('#add-banner-btn');        // 新增横幅
      // const confirmUploadBtn = e.target.closest('#confirm-upload');      // 确认上传横幅图片(后来没用了)
      if (editBtn) {enterEditMode(editBtn)}         // 编辑
      if (saveBtn) {saveBanner(saveBtn)}            // 保存
      if (cancelBtn) {cancelEdit(cancelBtn)}        // 作废
      if (uploadBtn) {openUploadModal(uploadBtn)}   // 上传图片
      if (deleteBtn) {deleteBanner(deleteBtn)}      // 删除
      if (newBtn) {addNewBannerRow()}               // 新增横幅
      // if (confirmUploadBtn) {uploadBannerImage()}   // 确认上传横幅图片(后来没用了)
      // 7. 图片预览功能
      if (e.target.classList.contains('banner-preview')) {
          const modal = new bootstrap.Modal(container.querySelector('#imagePreviewModal'));
          const modalImg = container.querySelector('#modalImage');
          modalImg.src = e.target.dataset.url;
          modalImg.alt = e.target.alt;
          modal.show();
      }
      // 8. 点击关联商品编辑按钮
      if (!e.target.closest('.banner-product-container')) {
           closeSelect()
       }
      if (e.target.closest('.banner-product-container')) {
            // 先关闭已有的选择框
            const selectEL = e.target.closest('.banner-product-container')
            const selectID= selectEL.closest('tr').dataset.id

            if(parseInt(selectID) !== parseInt(activeSelectId) && parseInt(activeSelectId) !== 0){
                closeSelect()
            }
            const display = selectEL.querySelector('.product-display');
            const edit = selectEL.querySelector('.product-edit');

            // 标记已经打开了选择框
            activeSelectId = selectID;

            // 切换显示/编辑状态
            display.classList.add('d-none');
            edit.classList.remove('d-none');

            // 聚焦下拉框
            const select = edit.querySelector('.product-select');
            select.focus();
        }
      // 12.分页功能
      if (e.target.closest('.pagination-btn')) {
            e.preventDefault();
            // 获取容器作用域内的按钮
            const $btn = $container.find(e.target.closest('.pagination-btn'));
            // 使用上下文参数限定作用域
            const action = $btn.data('action');
            // 容器内获取分页数据
            const currentPage = parseInt($container.find('#current-page-display').text());
            const totalPages = parseInt($container.find('#total-pages-display').text());
            const keyw = container.querySelector('input[name="search"]');
            const keyword = keyw ? keyw.value.trim() : ''

            let newPage = currentPage;
            if (action === 'prev' && currentPage > 1) newPage = currentPage - 1;
            if (action === 'next' && currentPage < totalPages) newPage = currentPage + 1;

            if (newPage !== currentPage) {
                loadPage(newPage, keyword, $container);
            }
        }
      // 13.分页里的跳转按钮
      if (e.target.closest('#page-jump-btn')) {
            // 获取容器作用域内的按钮
            // const $btn = $container.find(e.target.closest('#page-jump-btn'));
            const targetPage = parseInt($container.find('#page-jump-input').val());
            const totalPages = parseInt($container.find('#total-pages-display').text());

            const keyw = container.querySelector('input[name="search"]');
            const keyword = keyw ? keyw.value.trim() : ''
            // const userEl = container.querySelector('#userTypeSelect')

            if (targetPage && targetPage >= 1 && targetPage <= totalPages) {
                loadPage(targetPage, keyword, $container);
            } else {
                // 输入验证提示
                const toast = `<div class="toast align-items-center text-white bg-danger border-0 position-fixed bottom-0 end-0 m-3" role="alert">
                    <div class="d-flex">
                        <div class="toast-body">请输入 1-${totalPages} 之间的有效页码</div>
                        <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast"></button>
                    </div>
                </div>`;

               $container.append(toast);
               $container.find('.toast').toast('show');
                setTimeout(() => $('.toast').toast('hide').remove(), 3000);
            }
        }
      // 14.预览图片(上传图片时,如果需要预览,再加上,本系统暂时没加上用)
      // if (e.target.id === 'banner-image') {
      //     previewImage(e.target.files[0]);
      //  }

    });

   // 13-1 回车键跳转支持(分页)
   $container.on('keypress', '#page-jump-input', function(e) {
        if (e.which === 13) {
            $container.find('#page-jump-btn').trigger('click');
        }
    });

   // 状态切换功能(启用与禁用), 关联商品下拉框变化
   container.addEventListener('change', function(e) {
      // 1. 状态切换功能(启用与禁用)
      if (e.target.classList.contains('toggle-status')) {
      const bannerId = e.target.dataset.id;
      const isActive = e.target.checked;

      fetch(`/ecom/banners/toggle-status/${bannerId}/`, {
        method: 'POST',
        headers: headers,
        body: JSON.stringify({ is_active: isActive })
      })
      .then(response => {
        if (!response.ok) throw new Error('状态更新失败');
        return response.json();
      })
      .then(data => {
        if (data.success) {
          // 更新状态标签文本
          const label = e.target.nextElementSibling;
          label.textContent = data.is_active ? '启用' : '禁用';
          showToast(`横幅已${data.is_active ? '启用' : '禁用'}`, data.is_active ? 'success' : 'warning');
        } else {
          throw new Error('状态更新失败');
        }
      })
      .catch(error => {
        e.target.checked = !isActive; // 恢复原始状态
        showToast('操作失败，请重试', 'error');
      });
    }
      // 2.监听关联商品下拉框变化 - 自动保存
      if (e.target.classList.contains('product-select')) {
            const select = e.target;
            const display = document.querySelector('.product-display');
            const edit = select.closest('.product-edit');
            const container = edit.closest('.banner-product-container');
            const bannerId = container.closest('tr').dataset.id;
            const productId = select.value;
           // 自动保存
            saveProductAssociation(bannerId, productId, container);
        }
  });

   // 6. 搜索表单提交 (AJAX)
   container.addEventListener('submit', function(e) {
      if(e.target.id === 'banner-search-form') {
        e.preventDefault();
        // 获取搜索值的新方法
        const searchTerm = e.target.elements.search.value.trim();
        if(searchTerm) {
          fetchBanners({ search: searchTerm });
        } else {
          fetchBanners();
        }
      }
    });

   // 10.删除横幅
   function deleteBanner(button) {
     const row = button.closest('tr')
     const bannerId = row.dataset.id;
     const bannerTitle = row.querySelector('.banner-title').textContent.trim();
     // 高亮
     row.classList.add('table-danger');
     Swal.fire({
        title: '确认删除',
        text: `确定要删除横幅 "${bannerTitle}" 吗？此操作不可恢复。`,
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#d33',
        cancelButtonColor: '#3085d6',
        confirmButtonText: '确认删除',
        cancelButtonText: '取消'
      }).then((result) => {
        if (result.isConfirmed) {
           headers.apiKey = 'YOUR_API_KEY'
           headers.accessToken = 'USER_ACCESS_TOKEN_USER_ACCESS_TOKEN'
          fetch(`/ecom/banners/${bannerId}/delete/`, {
              method: 'POST',
              headers: headers,
            })
            .then(response => {
              if (response.ok) {
                showToast(`横幅"${bannerTitle}"已删除`, 'success');
                // 刷新横幅列表
                fetchBanners();
              } else {
                throw new Error('删除失败');
              }
            })
            .catch(error => {
              showToast('删除失败，请重试', 'error');
            });
        }else{
            // 移除高亮
            row.classList.remove('table-danger');
        }
      });
  }

   // 关闭已有的选择框
   function closeSelect(){
       if(activeSelectId){
            const targetRow = document.querySelector(`tr[data-id="${activeSelectId}"]`);
             if (!targetRow) {
                showToast(`未找到ID为 ${activeSelectId} 的横幅行`, 'error');
                return;
            }
             // 2. 在行内定位edit和display容器
            const edit = targetRow.querySelector('.product-edit');
            const display = targetRow.querySelector('.product-display');

            if (!edit || !display) {
                showToast(`未找到横幅 ${activeSelectId} 的商品编辑容器`, 'error');
                return;
            }
            // 切换显示/编辑状态
            edit.classList.add('d-none');
            display.classList.remove('d-none');

            // 5. 重置选择框状态
            activeSelectId = 0;

        }
   }

   // 保存商品关联关系
   function saveProductAssociation(bannerId, productId, container) {
    const display = container.querySelector('.product-display');
    const editButton = display.querySelector('.edit-product-btn');
    const edit = container.querySelector('.product-edit');
    const select = edit.querySelector('.product-select');

    // 发送请求到后端
    fetch(`/ecom/banners/${bannerId}/update-product/`, {
        method: 'POST',
        headers: headers,
        body: JSON.stringify({
            product_id: productId || null
        })
    })
    .then(response => {
        if (!response.ok) {
            throw new Error(`HTTP ${response.status}`);
        }
        return response.json();
    })
    .then(data => {
        if (data.success) {
            let productNameSpan = display.querySelector('.product-name');
            if (!productNameSpan) {
                  // 创建新元素
                  productNameSpan = document.createElement('span');
                  productNameSpan.className = 'product-name text-primary';
                  // 插入 DOM
                  display.insertBefore(productNameSpan, editButton);
            }

            let productIdSpan = display.querySelector('.product-id');
            if (!productIdSpan) {
                  // 创建新元素
                  productIdSpan = document.createElement('span');
                  productIdSpan.className = 'product-id';
                 // 在按钮前插入
                 display.insertBefore(productIdSpan, editButton);
            }

            if (productId && data.product_name) {
                // 更新产品名称显示
                productNameSpan.textContent = data.product_name.trim()
                productNameSpan.title = data.product_name.trim() + `(ID: ${productId})`;
                // 更新产品ID显示
                productIdSpan.textContent = `(ID: ${productId})`;
                // 显示产品信息
                productNameSpan.classList.remove('d-none');
                productIdSpan.classList.remove('d-none');

                // 隐藏"未关联"文本
                display.querySelector('.text-muted').classList.add('d-none');
            } else {
                // 显示"未关联"
                let mutedSpan = display.querySelector('.text-muted')
                if (!mutedSpan) {
                      // 创建新元素
                      mutedSpan = document.createElement('span');
                      mutedSpan.className = 'text-muted text-primary';
                      mutedSpan.textContent = '未关联';
                     // 在按钮前插入
                     display.insertBefore(mutedSpan, editButton);
                }

                mutedSpan.classList.remove('d-none');

                // 隐藏产品信息
                productNameSpan.classList.add('d-none');
                productIdSpan.classList.add('d-none');
            }

            // 切换回显示状态
            edit.classList.add('d-none');
            display.classList.remove('d-none');

            showToast('关联商品已更新', 'success');
        } else {
            throw new Error(data.message || '更新失败');
        }
    })
    .catch(error => {
        showToast(`保存失败: ${error.message}`, 'error');
    })
    .finally(() => {
        // 重置选择框状态
        activeSelectId = 0;
    });
}

   // 进入编辑模式
   function enterEditMode(button) {
      const bannerId = button.closest('tr').dataset.id;
      const row = container.querySelector(`#banner-row-${bannerId}`);

      // 保存原始数据
      originalData[bannerId] = {
        title: row.querySelector('.banner-title').textContent,
        order: row.querySelector('.banner-order').textContent
      };

      // 切换显示元素
      row.classList.add('editing-row');
      row.querySelector('.banner-title').classList.add('d-none');
      row.querySelector('.banner-title-edit').classList.remove('d-none');
      row.querySelector('.banner-order').classList.add('d-none');
      row.querySelector('.banner-order-edit').classList.remove('d-none');
      row.querySelector('.image-upload-btn').classList.remove('d-none');

      // 赋值给原来没有赋值的标题和优先级
      row.querySelector('.banner-title-edit').value = originalData[bannerId].title
      row.querySelector('.banner-order-edit').value = originalData[bannerId].order

      // 切换按钮
      button.closest('.edit-banner').classList.add('d-none');
      row.querySelector('.delete-banner').classList.add('d-none');
      row.querySelector('.save-banner').classList.remove('d-none');
      row.querySelector('.cancel-edit').classList.remove('d-none');

      currentEditRow = row;
    }

   // 退出编辑模式
   function exitEditMode(row) {
      const bannerId = row.dataset.id;
      // 恢复显示元素
      row.classList.remove('editing-row');
      row.querySelector('.banner-title').classList.remove('d-none');
      row.querySelector('.banner-title-edit').classList.add('d-none');
      row.querySelector('.banner-order').classList.remove('d-none');
      row.querySelector('.banner-order-edit').classList.add('d-none');
      row.querySelector('.image-upload-btn').classList.add('d-none');

      // 恢复按钮
      row.querySelector('.edit-banner').classList.remove('d-none');
      row.querySelector('.delete-banner').classList.remove('d-none');
      row.querySelector('.save-banner').classList.add('d-none');
      row.querySelector('.cancel-edit').classList.add('d-none');
      // 删除原保存的数据
      delete originalData[bannerId];
      currentEditRow = null;
    }

   // 保存横幅数据
   function saveBanner(button) {
    const bannerId = button.closest('tr').dataset.id;
    const row = container.querySelector(`#banner-row-${bannerId}`);
    const isNew = bannerId === 'new';
    // 收集数据
    const data = {
        title: row.querySelector('.banner-title-edit').value,
        order: parseInt(row.querySelector('.banner-order-edit').value),
        is_active: row.querySelector('.toggle-status').checked,
        product_id: row.querySelector('.product-select').value || null
    };

    // 数据验证
    const errors = validateBannerData(data);
    if (errors.length > 0) {
        showToast(`数据验证失败: ${errors.join(', ')}`, 'error');
        return;
    }

    // AJAX保存数据
    const url = isNew ? '/ecom/banners/create/' : `/ecom/banners/${bannerId}/update/`;
    const method = isNew ? 'POST' : 'PUT';
    fetch(url, {
        method: method,
        headers: headers,
        body: JSON.stringify(data)
    })
    .then(response => {
        // 处理 HTTP 错误状态
        if (!response.ok) {
            return response.json().then(err => {
                throw new Error(`HTTP ${response.status}: ${err.message || '未知错误'}`);
            });
        }
        return response.json();
    })
    .then(result => {
        if (result.success) {
            // 更新行数据
            if (isNew) {
                row.dataset.id = result.id;
                row.id = `banner-row-${result.id}`;
                row.querySelector('td:first-child').textContent = result.id;
                row.classList.add('new-banner-row');
                setTimeout(() => row.classList.remove('new-banner-row'), 2000);
            }
            // 更新显示数据
            row.querySelector('.banner-title').textContent = data.title;
            row.querySelector('.banner-order').textContent = data.order;
            exitEditMode(row);
            showToast(isNew ? '横幅添加成功' : '横幅更新成功', 'success');
        } else {
            showToast('操作失败: ' + result.message, 'error');
        }
    })
    .catch(error => {
        showToast('网络请求失败', 'error');
    })
    .finally(() => {
      const searchAndPage = container.querySelector('.searchAndPage');
      // 显示底部栏
      searchAndPage.classList.remove('d-none');
    });
    }

   // 数据验证函数
   function validateBannerData(data) {
        const errors = [];

        // 标题验证
        if (!data.title || data.title.trim().length < 2) {
            errors.push('标题至少需要2个字符');
        }

        // 优先级验证
        if (isNaN(data.order) || data.order < 0) {
            errors.push('优先级必须是非负整数');
        }

        // 关联商品验证（可选）
        if (data.product_id && isNaN(parseInt(data.product_id))) {
            errors.push('关联商品ID无效');
        }

        return errors;
    }

   // 取消编辑
   function cancelEdit(button) {
      const bannerId = button.closest('tr').dataset.id;
      const row = document.getElementById(`banner-row-${bannerId}`);

      if (bannerId === 'new') {
        // 新增行直接删除
        row.remove();
      } else {
        // 恢复原始数据
        row.querySelector('.banner-title-edit').value = originalData[bannerId].title;
        row.querySelector('.banner-order-edit').value = originalData[bannerId].order;
        exitEditMode(row);
      }
      // 显示底部栏
      const searchAndPage = container.querySelector('.searchAndPage');
      searchAndPage.classList.remove('d-none');
    }

   // 添加新横幅行
   function addNewBannerRow() {
      const searchAndPage = container.querySelector('.searchAndPage');
      // 隐藏底部栏
      searchAndPage.classList.add('d-none');
      const newRow = container.querySelector('#new-banner-row').cloneNode(true);
      // 显示新增行
      newRow.classList.remove('d-none');
      newRow.id = 'banner-row-new';
      // document.getElementById('banners-body').appendChild(newRow);
      const tbody = container.querySelector('#banners-body')
      const firstChild = tbody.firstElementChild;

      if (firstChild) {
          tbody.insertBefore(newRow, firstChild);  // 插入到现有首行前
        } else {
        tbody.appendChild(newRow);  // 表格为空时直接添加
      }
    }

   // 打开图片上传模态框
   function openUploadModal(button) {
      const row = button.closest('tr');
      document.getElementById('current-banner-id').value = row.dataset.id;
      // 每次创建新input元素
      const newInput = document.getElementById('image-upload-input').cloneNode(true);
      document.getElementById('image-upload-input').replaceWith(newInput);
      newInput.addEventListener('change', handleFileUpload);
     // 设置bannerID并触发
     // const row = uploadBtn.closest('tr');
     newInput.dataset.bannerId = row.dataset.id;
     newInput.click();
     // 禁用按钮防止重复提交（解决异步问题）
     // button.disabled = true;
    }

   // 上传横幅图片处理函数
   function handleFileUpload(e) {
        const file = e.target.files[0];
        if (!file) return;
        // 立即重置
        e.target.value = '';
        const bannerId = e.target.dataset.bannerId;
        uploadBannerImage(bannerId, file);
    }

   // 图片上传函数
   function uploadBannerImage(bannerId, file) {
        const isNewBanner = bannerId === "new";
        const formData = new FormData();
        formData.append('image', file);
        formData.append('is_new', isNewBanner.toString());
        // 新增时发送空ID，更新时发送真实ID
        if (!isNewBanner) {
            formData.append('banner_id', bannerId);
        }
        // 禁止手动设置Content-Type
        const headers = new Headers();
        headers.append('X-CSRFToken', getCSRFToken());
        fetch('/ecom/banners/upload-image/', {
            method: 'POST',
            headers: headers,
            body: formData
        })
        .then(response => {
            if(!response.ok) return Promise.reject(response.message);
            return response.json(); // 如果成功，继续处理
        })
        .then(data => {
            if (data.success) {
                if (isNewBanner) {
                    // 如果是新增,就直接刷新页面,请求第一页
                    loadPage(1, '', $container)
                }else{
                    bannerId = data.new_banner_id;
                    // 更新图片显示
                    const row = container.querySelector(`#banner-row-${bannerId}`);
                    const img = row.querySelector('.banner-preview') || document.createElement('img');
                    img.src = data.image_url;
                    img.alt = "横幅图片";
                    img.classList.add('img-thumbnail', 'banner-preview');
                    img.style.maxWidth = '80px';
                    img.style.cursor = 'pointer';
                    if (!row.querySelector('.banner-preview')) {
                        row.querySelector('.banner-image-container').prepend(img);
                        row.querySelector('.text-muted').classList.add('d-none');  // 默认的无图片不显示
                    }
                    // 图片更新完毕,随即点击"取消"以恢复原来状态
                    const cancel = row.querySelector('.cancel-edit')
                    if(cancel) {
                        cancelEdit(cancel)
                    }

                }
                showToast('图片上传成功', 'success');
            } else {
                showToast('图片上传错误: ' + data.message, 'error');
                console.error('图片上传错误: ', data.message)
            }
        })
        .catch(error => {
            showToast('图片上传失败', 'error');
        })
        .finally(() => {

    });
    }

   // 预览图片(上传图片时,需要预览再加上)
   // function previewImage(file) {
   //    if (file) {
   //      const reader = new FileReader();
   //      reader.onload = function (e) {
   //        const preview = document.getElementById('image-preview');
   //        preview.src = e.target.result;
   //        preview.classList.remove('d-none');
   //      };
   //      reader.readAsDataURL(file);
   //    }
   //  }

   // 获取CSRF Token的函数
   function getCSRFToken() {
      const csrftoken = document.cookie.match(/csrftoken=([^;]+)/)?.[1]
          || document.querySelector('meta[name="csrf-token"]')?.content;
       return csrftoken || '';
   }

   // 辅助函数：获取横幅列表
   function fetchBanners(params = {}) {
        // 添加搜索参数识别标志
        params.is_ajax = true;
        const url = new URL('/ecom/banners/list/', window.location.origin);
        Object.keys(params).forEach(key => {url.searchParams.append(key, params[key]);});

        fetch(url, {headers })
        .then(response => {
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            return response.json();})
        .then(data => {
            if (data.html) {
                // 更新横幅列表容器
                $container.find('.banner_list_son').html(data.html);

                const searchTerm = params.search || '';
                if (searchTerm) {
                    // 更新搜索框原来的搜索词
                    const input = container.querySelector('input[name="search"]');  // 通过name属性定位（避免class冲突）
                    if (input) {
                        input.value = searchTerm;
                    }

                    // 高亮搜索关键字
                    highlightSearchResults(searchTerm);
                }
            }
        })
        .catch(error => {
            showToast('搜索失败，请重试', 'error');
        });
    }

   // 高亮搜索结果函数
   function highlightSearchResults(searchTerm) {
      const bannersTable = container.querySelector('#banners-body');
      const titleElements = bannersTable.querySelectorAll('.banner-title');

      titleElements.forEach(element => {
        const originalHTML = element.innerHTML;
        const regex = new RegExp(searchTerm, 'gi'); //g全局 i不分大小写
        element.innerHTML = originalHTML.replace(
            regex,
            match => `<span class="search-highlight">${match}</span>`
        );
    });
   }

   // 12-1 加载指定页数据
   function loadPage(page, keyword, $container) {
        // 显示加载状态
        const loadingToast = `<div class="toast align-items-center text-white bg-primary border-0 position-fixed bottom-0 end-0 m-3" role="status">
            <div class="d-flex">
                <div class="toast-body">正在加载第 ${page} 页数据...</div>
                <div class="spinner-border spinner-border-sm text-light me-2 m-auto"></div>
            </div>
        </div>`;

      $container.append(loadingToast);
      $container.find('.toast').toast('show');

        // AJAX请求数据 window.location.pathname
        const API_BASE = window.location.origin;
        $.ajax({
            url: `${API_BASE}/ecom/banners/list/`,
            type: 'GET',
            data:{
                is_ajax: '1',
                page: page,
                search: keyword,
            },
            headers: headers,
            success: function(response) {
              // 更新表格内容
              $container.find('.banner_list_son').html(response.html);
              // 更新搜索框原来的搜索词
              const input = container.querySelector('input[name="search"]');  // 通过name属性定位（避免class冲突）
                if (input) {
                    input.value = keyword;
                }

              // 更新分页信息
              $container.find('#current-page-display').text(response.pagination.current_page);
              $container.find('#total-pages-display').text(response.pagination.total_pages);
              $container.find('#total-pages').text(response.pagination.total_pages);
              $container.find('#total-items').text(response.pagination.total_items);

              // 更新按钮状态
              $container.find('[data-action="prev"]')
                  .prop('disabled', !response.pagination.has_prev)
                  .toggleClass('disabled', !response.pagination.has_prev);
              $container.find('[data-action="next"]')
                  .prop('disabled', !response.pagination.has_next)
                  .toggleClass('disabled', !response.pagination.has_next);

              // 更新输入框范围
              $container.find('#page-jump-input').attr('max', response.pagination.total_pages).val('');

              // 显示成功提示
              const successToast = `<div class="toast align-items-center text-white bg-success border-0 position-fixed bottom-0 end-0 m-3" role="alert">
                    <div class="d-flex">
                        <div class="toast-body">已加载第 ${page} 页数据</div>
                        <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast"></button>
                    </div>
                </div>`;
              $container.append(successToast);
              $container.find('.toast').toast('show');
              setTimeout(() => $('.toast').toast('hide').remove(), 2000);},
                error: function(xhr) {
                    console.error("分页加载错误:", xhr.statusText);
                        const errorToast = `<div class="toast align-items-center text-white bg-danger border-0 position-fixed bottom-0 end-0 m-3" role="alert">
                        <div class="d-flex">
                            <div class="toast-body">数据加载失败，请重试</div>
                            <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast"></button>
                        </div>
                    </div>`;
                  $container.append(errorToast);
                  $container.find('.toast').toast('show');
              setTimeout(() => $('.toast').toast('hide').remove(), 3000); },
            complete: function() {
                // 移除加载提示
                $container.find('.toast').toast('hide').remove();
            }
        });
    }

}
})();